/*
 *  Process.cpp
 *  vorpal
 *
 *  Created by Russell Y Webb on 4/05/09.
 *  Copyright 2009 UC. All rights reserved.
 *
 */

#include "Module.h"

namespace Vorpal{
	
	/* in System:
	 case msg_module: {
		 if(numArgs < 2){ Failure(ERR_INVALID_NUM_ARGS); }
		 Handle<String> path = Translate<String>(vm->FromTop(0));
		 vm->Drop(numArgs);
		 vm->PushNew( new Module(path->ToCString()) );
		 return true;
		 break;
	 }	 
	*/
	
	static Handle<Object> ProcessCopy(Handle<Object> &source){
		if(typeid(*source.Ptr()) == typeid(Number)){
			return Handle<Object>( new Number(Translate<Number>(source).Ptr()->Value()) );
		}
		else if(typeid(*source.Ptr()) == typeid(String)){
			return Handle<Object>( new String(Translate<String>(source).Ptr()->ToString()) );
		}
		else{
			Failure(ERR_INVALID_ARG_TYPES);
		}		
		return Handle<Object>(0);
	}
	
	bool Module::Receive(Message msg, uint32_t numArgs, VM *vm){
		Handle<Object> args[numArgs];
		loop(i, 1, numArgs){
			args[i - 1] = ProcessCopy(vm->FromTop(-numArgs + 1 + i));
		}
		vm->Drop(numArgs);
		Handle<Object> result = vm->Execute(msg, sys, sys, numArgs - 1, args);
		if(typeid(*result.Ptr()) == typeid(Number) || typeid(*result.Ptr()) == typeid(String)){
			Handle<Object> copiedResult = ProcessCopy(result);
			vm->Push(copiedResult);
		}
		else{
			Failure(ERR_INVALID_ARG_TYPES);
		}
		return true;
	}
	
}

